using UnityEngine;

//塔
public abstract class Tower : GameTileContent
{

    //攻击范围
    [SerializeField, Range(1.5f, 10.5f)]
    protected float targetingRange = 1.5f;
    
    //enemyc层   位掩码
    const int enemyLayerMask = 1<<9;

    //跟踪目标缓冲区
    static Collider[] targetsBuffer = new Collider[100];



    void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.yellow;
        Vector3 position = transform.localPosition;
        position.y += 0.01f;
        Gizmos.DrawWireSphere(position, targetingRange);
    }

    //获取目标
    protected bool AcquireTarget(out TargetPoint target)
    {
        // Vector3 a = transform.localPosition;
        // Vector3 b = a;
        // b.y += 3f;
        // //在物理世界中检查给定胶囊体，并在用户提供的缓冲区中返回所有重叠的碰撞体。
        // //返回写入缓冲区的条目的数量。
        // int hits = Physics.OverlapCapsuleNonAlloc(
        //     a, b, targetingRange,targetsBuffer ,enemyLayerMask
        // );

        // if(hits > 0)
        // {
        //     target =targetsBuffer[Random.Range(0,hits)].GetComponent<TargetPoint>();
        //     Debug.Assert(target != null, "Targeted non-enemy!", targetsBuffer[0]);
        //     return true;
        // }
        // target = null;
        // return false;

        if (TargetPoint.FillBuffer(transform.localPosition, targetingRange)) {
			target = TargetPoint.RandomBuffered;
			return true;
		}
		target = null;
		return false;
    }

    //是否锁定目标
    protected bool TrackTarget(ref TargetPoint target)
    {
        if(target == null || !target.Enemy.IsValidTarget)
            return false;
        Vector3 a = transform.localPosition;
        Vector3 b = target.Position;
        float x = a.x - b.x;
        float z = a.z - b.z;
        float r = targetingRange + 0.125f * target.Enemy.Scale;//碰撞器半径 * 缩放
        if(x * x + z * z > r * r) 
        {
            target = null;
            return false;
        }
        return true;
    }

    public abstract TowerType TowerType{get;}

}